<?php

class FormUserLogin extends CFormModel
{
	public $email;
	public $password;
	public $rememberMe;

	public function rules()
	{
		return array(
			array('email', 'required'),
			
			array('password', 'required'),
			array('password', 'validateAuth'),
			
			array('rememberMe', 'boolean'),
		);
	}

	public function attributeLabels()
	{
		return array(
			'email'      => UserModule::t('E-mail'),
			'password'   => UserModule::t('Password'),
			'rememberMe' => UserModule::t('Remember me'),
		);
	}

	public function validateAuth($attribute, $params)
	{
		if(!$this->hasErrors())
		{
			$duration = 0;
			
			if($this->rememberMe)
			{
				$duration = Yii::app()->getModule('user')->settings['cookie']['duration'];
			}
			
			$identity = new UserIdentity($this->email, $this->password);
			$identity->authenticate($duration);
			
			switch($identity->errorCode)
			{
				case UserIdentity::ERROR_NONE:
					$model = User::model()->notsafe()->findByPk(Yii::app()->user->id);
					if($model)
					{
						return $model->logActivity();
					}
					break;
				case UserIdentity::ERROR_UNKNOWN_IDENTITY:
					$this->addError('email', UserModule::t('Authentication data is invalid'));
					break;
				case UserIdentity::ERROR_STATUS_INTACTIV:
					$this->addError('email', UserModule::t('Your account has not been activated yet'));
					break;
				case UserIdentity::ERROR_STATUS_PENDING:
					$this->addError('email', UserModule::t('Your account is still pending'));
					break;
				case UserIdentity::ERROR_STATUS_BANNED:
					$this->addError('email', UserModule::t('Your account has been banned'));
					break;
			}
		}
	}
	
}
